package com.example.springboot01;


import java.io.*;

/**
 * 执行操作系统 shell 脚本以及命令的工具类
 */
public final class ShellUtil {

    private ShellUtil() {

    }

    /**
     * 执行指令
     *
     * @param command 指令
     * @return 执行响应结果
     */
    public static String executeCommand(String command) {
        try {
            StringBuilder result = new StringBuilder();
            ProcessBuilder pb;
            String os = System.getProperty("os.name");
            if (os.toLowerCase().contains("win")) {
                pb = new ProcessBuilder().command("cmd", "/c", command);
            } else {
                pb = new ProcessBuilder().command("/bin/sh", "-c", command);
            }
            pb.redirectErrorStream(true);
            Process p = pb.start();
            p.waitFor();
            InputStream is = p.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line).append(System.lineSeparator());
            }
            p.waitFor();
            is.close();
            reader.close();
            p.destroy();
            return result.toString();
        } catch (InterruptedException | IOException ex) {
            throw new RuntimeException("call error");
        }
    }


    /**
     * 执行指令
     *
     * @param path    指令执行的路径
     * @param command 指令
     * @return 执行响应结果
     */
    public static String executeCommand(String command, String path) {
        try {
            StringBuilder result = new StringBuilder();
            ProcessBuilder pb;
            String os = System.getProperty("os.name");
            if (os.toLowerCase().contains("win")) {
                pb = new ProcessBuilder().command("cmd", "/c", command).directory(new File(path));
            } else {
                pb = new ProcessBuilder().command("/bin/sh", "-c", command).directory(new File(path));
            }
            pb.redirectErrorStream(true);
            Process p = pb.start();
            p.waitFor();
            InputStream is = p.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                result.append(line).append(System.lineSeparator());
            }
            p.waitFor();
            is.close();
            reader.close();
            p.destroy();
            return result.toString();
        } catch (InterruptedException | IOException ex) {
            throw new RuntimeException("call error");
        }
    }

    public static void main(String[] args) {
        //System.out.println(executeCommand(" D:\\aconda\\python C:\\Users\\ohq\\Desktop\\JAVAFX\\springboot01\\src\\test\\java\\com\\example\\springboot01\\test.py 1 2"));
        System.out.println( executeCommand("java -version"));
    }

}
